#!/bin/sh
# SPDX-License-Identifier: LGPL-2.1+

set -eu
[ -n "${DEBUG:-}" ] && set -x

PASS=0

cleanup() {
    [ "$PASS" = "1" ] || (echo FAIL && exit 1)
}

trap cleanup EXIT HUP INT TERM

LXCFSDIR=${LXCFSDIR:-/var/lib/lxcfs}

if ! mountpoint -q ${LXCFSDIR}; then
    echo "lxcfs isn't mounted on ${LXCFSDIR}"
    exit 1
fi

IS_CGROUP_V2=0
grep -qF 'cgroup cgroup' /proc/1/mountinfo || IS_CGROUP_V2=1

if [ "$IS_CGROUP_V2" = "1" ]; then
    echo "==> Setting up cgroup in lxcfs_test_proc"
    [ ! -d /sys/fs/cgroup ] && exit 0

    default_hierarchy="/"

    hierarchy_path=/sys/fs/cgroup/${default_hierarchy}
    cpupath=${hierarchy_path}
    mempath=${hierarchy_path}

    rmdir ${hierarchy_path}/lxcfs_test_proc 2>/dev/null || true
    mkdir ${hierarchy_path}/lxcfs_test_proc

    echo 1 > ${hierarchy_path}/lxcfs_test_proc/cgroup.procs

    echo '+cpu +cpuset +memory' > ${hierarchy_path}/cgroup.subtree_control

    memory_limit_file=memory.max
else
    echo "==> Setting up memory/cpuset cgroup in lxcfs_test_proc"
    [ ! -d /sys/fs/cgroup/memory ] && exit 0
    [ ! -d /sys/fs/cgroup/cpuset ] && exit 0

    initcpuset=$(awk -F: '/cpuset/ { print $3 }' /proc/1/cgroup)
    initmemory=$(awk -F: '/memory/ { print $3 }' /proc/1/cgroup)

    cpupath=/sys/fs/cgroup/cpuset/${initcpuset}
    mempath=/sys/fs/cgroup/memory/${initmemory}

    rmdir ${cpupath}/lxcfs_test_proc 2>/dev/null || true
    rmdir ${mempath}/lxcfs_test_proc 2>/dev/null || true
    mkdir ${cpupath}/lxcfs_test_proc
    mkdir ${mempath}/lxcfs_test_proc

    echo 1 > ${cpupath}/lxcfs_test_proc/tasks
    echo 1 > ${mempath}/lxcfs_test_proc/tasks

    memory_limit_file=memory.limit_in_bytes
fi

echo $((64*1024*1024)) > ${mempath}/lxcfs_test_proc/${memory_limit_file}
echo 0 > ${cpupath}/lxcfs_test_proc/cpuset.cpus

# Test that readdir on /proc basically works
echo "==> Testing directory listing on /proc"
ls -l ${LXCFSDIR}/proc | grep uptime
ls -l ${LXCFSDIR}/proc | grep cpuinfo
ls -l ${LXCFSDIR}/proc | grep stat
ls -l ${LXCFSDIR}/proc | grep meminfo

# Test uptime
echo "==> Testing /proc/uptime"
grep -Eq "^0.[0-9]{2} 0.[0-9]{2}$" ${LXCFSDIR}/proc/uptime

# Test cpuinfo
echo "==> Testing /proc/cpuinfo"
[ "$(grep "^processor" ${LXCFSDIR}/proc/cpuinfo | wc -l)" = "1" ]
grep -q "^processor.*0$" ${LXCFSDIR}/proc/cpuinfo || grep -q "^processor 0:.*" ${LXCFSDIR}/proc/cpuinfo

echo "==> Testing /sys/devices/system/cpu/online"
[ "$(cat ${LXCFSDIR}/sys/devices/system/cpu/online)" = "$(cat ${cpupath}/lxcfs_test_proc/cpuset.cpus)" ]

# Test stat
echo "==> Testing /proc/stat"
[ "$(grep "^cpu" ${LXCFSDIR}/proc/stat | wc -l)" = "2" ]

# Test meminfo
echo "==> Testing /proc/meminfo"
grep -q "^MemTotal.*65536 kB$" ${LXCFSDIR}/proc/meminfo

PASS=1
